from config import *

class Synapse:
	def __init__(self, cfg, emmiter, receiver):
		self.cfg = cfg
		self.emitter = emmiter
		self.receiver = receiver
		self.terminals = []
		for x in xrange(cfg.nna_nit):
			self.terminals.append(Terminal(self, cfg.c.r01(self.cfg.p), cfg.c.r01(self.cfg.p) * cfg.terminal_weight_max, self.cfg.tau))
		self.neighborhood()

	def terminal_weights_avg(self):
		sum = 0
		for terminal in self.terminals:
			sum += terminal.weight
		return sum/len(self.terminals)

	def count_neigbors(self,delay,r = 0):
		if not r : r = self.cfg.neighborhood_size
		return len([x for x in self.terminals if abs(delay - x.delay) <= r])

	def get_nearest_neigbor(self, delay):
		mint = None
		mdistance = 2
		for t in self.terminals:
			rdistance = abs(delay - t.delay)
			if rdistance < mdistance :
				mint = t
				mdistance = rdistance
		return mint

	def neighborhood(self,delay = -1):
		maxn = self.cfg.neighborhood_maxn
		power = self.cfg.neighborhood_power
		m = 1.0
		if delay > 0:
			if self.cfg.new: 
				self.terminals.append(Terminal(self, delay, 0, self.cfg.tau))
			m = min(self.count_neigbors(delay) ** power,maxn)
		#for t in self.terminals:
		#	t.width = self.cfg.tau / m
		return m or 1.0


class Terminal:
	 def __init__(self, synapse, delay = 0.0, weight = 0.0, width=0.0):
	 	self.delay = delay
	 	self.weight = weight
	 	self.width = width
	 	self.synapse = synapse
